package com.jsbs.iam.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jsbs.iam.auth.constant.Constants;
import com.jsbs.iam.auth.dto.IamDynamicUserGroupAddDto;
import com.jsbs.iam.auth.dto.IamDynamicUserGroupEditDto;
import com.jsbs.iam.auth.dto.IamOrgInfoQueryDto;
import com.jsbs.iam.auth.param.IamQueryDynamicUserGroupBeforeParam;
import com.jsbs.iam.auth.param.IamQueryDynamicUserGroupUsersParam;
import com.jsbs.iam.auth.param.IamQueryStaticUserGroupParam;
import com.jsbs.iam.auth.param.IamStaticUserGroupDeleteParam;
import com.jsbs.iam.auth.service.IamDynamicUserGroupManagerService;
import com.jsbs.iam.auth.service.IamRoleManagerService;
import com.jsbs.iam.auth.service.IamStaticUserGroupManagerService;
import com.jsbs.iam.auth.vo.*;
import com.jsbs.iam.common.core.dto.Result;
import com.jsbs.iam.common.core.utils.Json;
import com.jsbs.iam.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: DynamicUserGroupManagerController
 * @Author: tenghuawei
 * @Date: 2023/1/6 10:29
 * @Description:
 */

@Slf4j
@RestController
@RequestMapping("/iam/auth/dynamic/userGroupManager")
@SuppressWarnings("all")
public class IamDynamicUserGroupManagerController extends BaseController{

    @Autowired
    IamDynamicUserGroupManagerService iamDynamicUserGroupManagerService;

    @Autowired
    IamStaticUserGroupManagerService userGroupManagerService;

    @Autowired
    IamStaticUserGroupManagerService iamStaticUserGroupManagerService;

    @Autowired
    IamRoleManagerService iamRoleManagerService;

    /**
     * 功能描述：获取某组织类型下的组织树
     * @param
     * @return Result
     */
//    @LogDb
    @PostMapping("/getOrgTypeInfo")
    public Result getOrgTypeInfo (HttpServletRequest request) {
        IamOrgInfoQueryDto iamOrgInfoQueryDto = new IamOrgInfoQueryDto();
        try {
            //归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }

            // 组织树中包含岗位
            iamOrgInfoQueryDto.setIncludePost(Boolean.TRUE);
            iamOrgInfoQueryDto.setCompanyCode(companyCode);

            // 当前普管用户的所属的 管理员角色编码
            String adminRoleCode = request.getHeader(Constants.ADMIN_ROLE_CODE);
            // todo 普管角色的用户 先使用伪数据
            adminRoleCode="JS0004"; // JS0004=> 0000000001
            // 查询该普管用户的 组织范围权限列表 + 应用范围权限列表
            Result result = iamRoleManagerService.queryAdminRole(adminRoleCode, companyCode);
            AdminRoleVo adminRoleVo = JSONObject.parseObject(Json.toJsonString(result.getData()),AdminRoleVo.class);
            // 查询当前登录普管用户的组织范围权限列表
            List<IamAdminRoleOrgInfoVo> orgRoleList = adminRoleVo.getOrgRoleList();
            ArrayList<Object> list = new ArrayList<>();
            // 当前普管用户的组织类型编码（请求头中暂时没放组织类型编码）
//            iamOrgInfoQueryDto.setOrgTypeCode(orgRoleList.get(0).getOrgTypeCode());
            iamOrgInfoQueryDto.setOrgTypeCode("zzlx000003");
            log.info("Route==>DynamicUserGroupManagerController method=>getOrgTypeInfo 查询组织树入参：{}",Json.toJsonString(iamOrgInfoQueryDto));
            List<OrgThreeInfoVo> orgTypeInfos = iamDynamicUserGroupManagerService.getOrgTypeInfo(iamOrgInfoQueryDto);
            return Result.success("获取该组织类型下的组织树成功！",orgTypeInfos);
        }catch (Exception e){
            log.error("Route=>DynamicUserGroupManagerController method=>getOrgTypeInfo 查询组织树异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamOrgInfoQueryDto));
            return handleException(e,e.getMessage());
        }
    }


    /**
     * 功能描述：新增动态用户组
     * @param staticUserGroupAddDto
     * @return Result
     */
    // todo 新增动态用户组
    @PostMapping("/createDynamicUserGroup")
    public Result createDynamicUserGroup (HttpServletRequest request, @RequestBody IamDynamicUserGroupAddDto iamDynamicUserGroupAddDto) {
        try {
            String adminRoleCode = request.getHeader(Constants.ADMIN_ROLE_CODE);
            if(StringUtils.isBlank(adminRoleCode)){
                return Result.failWithMsg("管理员角色编码不可为空！");
            }
            // 获取当前登录人
            String userName = (String) request.getHeader(Constants.NAME);
            // 先使用伪数据
//            userName="admin";
            if (StringUtils.isBlank(userName)) {
                return Result.failWithMsg("当前登录状态异常！");
            }
            //当前登录人的所属归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            // companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            if(StringUtils.isBlank(iamDynamicUserGroupAddDto.getUserGroupName())){
                return Result.failWithMsg("用户组名称不可为空！");
            }
            if(StringUtils.isNotBlank(iamDynamicUserGroupAddDto.getUserGroupInfo()) && iamDynamicUserGroupAddDto.getUserGroupInfo().length()>200){
                return Result.failWithMsg("  动态用户组长度最大不超过200！");
            }
            // 创建人
            iamDynamicUserGroupAddDto.setCreatePerson(userName);
            // 普管角色编码
            iamDynamicUserGroupAddDto.setAdminRoleCode(adminRoleCode);
            // 租户
            iamDynamicUserGroupAddDto.setCompanyCode(companyCode);
            log.info("Route=>DynamicUserGroupManagerController method=>createDynamicUserGroup 创建动态用户组入参为：{}",Json.toJsonString(iamDynamicUserGroupAddDto));
            iamDynamicUserGroupManagerService.createDynamicUserGroup(iamDynamicUserGroupAddDto);
            log.info("Route=>DynamicUserGroupManagerController method=>createDynamicUserGroup 创建动态用户组成功！");
            return Result.successWithMsg("创建动态用户组成功！");
        }catch (Exception e){
            log.error("Route=>DynamicUserGroupManagerController method=>createDynamicUserGroup 创建动态用户组异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamDynamicUserGroupAddDto));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：查询动态用户组
     * @param iamQueryStaticUserGroupParam
     * @return Result
     */
    @PostMapping("/queryUserGroup")
    public Result queryUserGroup (HttpServletRequest request, @RequestBody IamQueryStaticUserGroupParam iamQueryStaticUserGroupParam) {
        try {
            String adminRoleCode = request.getHeader(Constants.ADMIN_ROLE_CODE);
            if(StringUtils.isBlank(adminRoleCode)){
                return Result.failWithMsg("管理员角色编码不可为空！");
            }
            //归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            iamQueryStaticUserGroupParam.setAdminRoleCode(adminRoleCode);
            iamQueryStaticUserGroupParam.setCompanyCode(companyCode);
            log.info("Route==>DynamicUserGroupManagerController method=>queryUserGroup 查询用户组入参：{}",Json.toJsonString(iamQueryStaticUserGroupParam));
            PageInfo<IamUserGroupVo> iamUserGroupVoPageInfo = iamDynamicUserGroupManagerService.queryDynamicUserGroup(iamQueryStaticUserGroupParam);
            if(0==iamUserGroupVoPageInfo.getTotal()){
                return Result.failWithMsg("无数据!");
            }
            return Result.success("查询用户组成功！",iamUserGroupVoPageInfo);
        }catch (Exception e){
            log.error("Route=>DynamicUserGroupManagerController method=>queryUserGroup 查询用户组异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamQueryStaticUserGroupParam));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：编辑动态用户组时，查询展示之前的数据-
     * @param iamQueryDynamicUserGroupBeforeParam
     * @return IamDynamicUserGroupVo
     */
    @PostMapping("/queryDynamicUserGroupEditBefore")
    public Result queryDynamicUserGroupEditBefore(HttpServletRequest request, @RequestBody IamQueryDynamicUserGroupBeforeParam iamQueryDynamicUserGroupBeforeParam) {
        try {
            //归属租户
//            String companyCode = (String) request.getSession().getAttribute("companyCode");
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
        iamQueryDynamicUserGroupBeforeParam.setCompanyCode(companyCode);
       IamDynamicUserGroupVo iamDynamicUserGroupVo = iamDynamicUserGroupManagerService.queryDynamicUserGroupEditBefore(iamQueryDynamicUserGroupBeforeParam);
        return Result.success("编辑动态用户组时，查询展示之前的数据成功！",iamDynamicUserGroupVo);
        }catch (Exception e){
            log.error("Route=>DynamicUserGroupManagerController method=>queryDynamicUserGroupEditBefore 编辑动态用户组时，查询展示之前的数据异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamQueryDynamicUserGroupBeforeParam));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：编辑动态用户组
     * @param iamDynamicUserGroupEditDto
     * @return Result
     */
    @PostMapping("/userGroupEdit")
    public Result userGroupEdit(HttpServletRequest request, @RequestBody IamDynamicUserGroupEditDto iamDynamicUserGroupEditDto) {
        try {
            // 获取当前登录人
            //String userName = (String) request.getSession().getAttribute("userName");
            String userName = (String) request.getHeader(Constants.NAME);
            //先使用伪数据
//            userName="admin";
            if (StringUtils.isBlank(userName)) {
                return Result.failWithMsg("当前登录状态异常！");
            }
            //归属租户
//            String companyCode = (String) request.getSession().getAttribute("companyCode");
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            if(StringUtils.isBlank(iamDynamicUserGroupEditDto.getUserGroupCode())){
                return Result.failWithMsg("用户组编码不可为空！");
            }
            if(StringUtils.isBlank(iamDynamicUserGroupEditDto.getUserGroupName()) || iamDynamicUserGroupEditDto.getUserGroupName().length()>20){
                return Result.failWithMsg("用户组名称不可为空，且最长不超过20字！");
            }
            if(StringUtils.isNotBlank(iamDynamicUserGroupEditDto.getUserGroupInfo()) && iamDynamicUserGroupEditDto.getUserGroupInfo().length()>200){
                return Result.failWithMsg("用户组描述最长不超过200字！");
            }
            iamDynamicUserGroupEditDto.setUpdatePerson(userName);
            iamDynamicUserGroupEditDto.setCompanyCode(companyCode);
            log.info("Route==>UserGroupManagerController method=>userGroupEdit 编辑动态用户组入参：{}",Json.toJsonString(iamDynamicUserGroupEditDto));
            iamDynamicUserGroupManagerService.userGroupEdit(iamDynamicUserGroupEditDto);
            return Result.successWithMsg("编辑动态用户组成功！");
        }catch (Exception e){
            log.error("Route=>DynamicUserGroupManagerController method=>userGroupEdit 编辑动态用户组异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamDynamicUserGroupEditDto));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：删除动态用户组
     * @param iamStaticUserGroupDeleteParam
     * @return Result
     */
    @PostMapping("/userGroupDelete")
    public Result userGroupDelete(HttpServletRequest request,@RequestBody IamStaticUserGroupDeleteParam iamStaticUserGroupDeleteParam) {
        try {
            String adminRoleCode = request.getHeader(Constants.ADMIN_ROLE_CODE);
            if(StringUtils.isBlank(adminRoleCode)){
                return Result.failWithMsg("管理员角色编码不可为空！");
            }
            //归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            if(StringUtils.isBlank(iamStaticUserGroupDeleteParam.getUserGroupCode())){
                return Result.failWithMsg("动态用户组编码不可为空，请选择一个动态用户组删除！");
            }
            iamStaticUserGroupDeleteParam.setAdminRoleCode(adminRoleCode);
            iamStaticUserGroupDeleteParam.setCompanyCode(companyCode);
            log.info("Route==>UserGroupManagerController method=>userGroupDelete 删除动态用户组入参：{}",Json.toJsonString(iamStaticUserGroupDeleteParam));
//            iamDynamicUserGroupManagerService.userGroupDelete(iamStaticUserGroupDeleteParam);
            iamStaticUserGroupManagerService.userGroupDelete(iamStaticUserGroupDeleteParam);
            return Result.successWithMsg("删除动态用户组成功！");
        }catch (Exception e){
            log.error("Route=>DynamicUserGroupManagerController method=>userGroupDelete 删除动态用户组异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamStaticUserGroupDeleteParam));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：查询动态用户组下的用户（分页展示）
     * @param iamQueryDynamicUserGroupUsersParam
     * @return Result todo thw 查看dt用户组的用户
     */
    @PostMapping("/queryDynamicUserGroupUserInfo")
    public Result queryDynamicUserGroupUserInfo(HttpServletRequest request, @RequestBody IamQueryDynamicUserGroupUsersParam iamQueryDynamicUserGroupUsersParam) {
        try {
            //归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            if(StringUtils.isBlank(iamQueryDynamicUserGroupUsersParam.getUserGroupCode())){
                return Result.failWithMsg("动态用户组编码不可为空，请选择一个动态用户组删除！");
            }
            iamQueryDynamicUserGroupUsersParam.setCompanyCode(companyCode);
            log.info("Route=>DynamicUserGroupManagerController method=>queryDynamicUserGroupUserInfo 查询动态用户组下的用户入参：{}", Json.toJsonString(iamQueryDynamicUserGroupUsersParam));
            PageInfo<IamUserInfoVo> pageInfo = iamDynamicUserGroupManagerService.queryDynamicUserGroupUserInfo(iamQueryDynamicUserGroupUsersParam);
            return Result.success("查询动态用户组下的用户成功！",pageInfo);
        }catch (Exception e){
            log.error("Route=>DynamicUserGroupManagerController method=>queryDynamicUserGroupUserInfo 查询动态用户组下的用户异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamQueryDynamicUserGroupUsersParam));
            return handleException(e,e.getMessage());
        }
    }



}
